package dep

import (
	"context"
	"runtime"
	"strings"
	"time"

	"gitee.com/go-errors/errors"
	"gitee.com/go-wena/wena/utils/archive"
	"gitee.com/go-wena/wena/utils/httpx"
)

const upxLatest = "https://v2.kkpp.cc/repos/upx/upx/releases/latest"
//https://api.github.com/repos/upx/upx/releases/latest

func DownloadNewestUpx(ctx context.Context, saveTo string, progress ...httpx.ProgressFunc) error {
	version, err := GetNewestUpxVersion(ctx)
	if err != nil {
		return err
	}

	extract := archive.New().DirectKind(version.Name).SaveTo(saveTo).WriteTo()
	process := httpx.ProcessProgress(extract, progress...)
	return httpx.Get(version.BrowserDownloadUrl).Process(process).Exec(ctx)
}

func GetNewestUpxVersion(ctx context.Context) (version *UpxVersion, err error) {
	var suffix string
	switch {
	case runtime.GOOS == "windows" && runtime.GOARCH == "amd64":
		suffix = "win64.zip"
	case runtime.GOOS == "windows" && runtime.GOARCH == "386":
		suffix = "win32.zip"
	case runtime.GOOS == "linux" && runtime.GOARCH == "amd64":
		suffix = "amd64_linux.tar.xz"
	case runtime.GOOS == "linux" && runtime.GOARCH == "386":
		suffix = "i386_linux.tar.xz"
	case runtime.GOOS == "linux" && runtime.GOARCH == "mips":
		suffix = "mips_linux.tar.xz"
	case runtime.GOOS == "linux" && runtime.GOARCH == "arm":
		suffix = "arm_linux.tar.xz"
	default:
		return nil, errors.Errorf("cannot download upx of %s_%s, you must download it manual", runtime.GOOS, runtime.GOARCH)
	}

	var tagFiles struct {
		Assets []*UpxVersion `json:"assets"`
	}

	err = httpx.Get(upxLatest).Process(httpx.ProcessJSON(&tagFiles)).Exec(ctx)
	if err != nil {
		return nil, err
	}

	for _, asset := range tagFiles.Assets {
		if strings.HasSuffix(asset.Name, suffix) {
			return asset, nil
		}
	}

	return
}

type UpxVersion struct {
	ID                 int64     `json:"id"`
	Name               string    `json:"name"`
	Size               int64     `json:"size"`
	State              string    `json:"state"`
	ContentType        string    `json:"content_type"`
	BrowserDownloadUrl string    `json:"browser_download_url"`
	Url                string    `json:"url"`
	CreatedAt          time.Time `json:"created_at"`
	UpdatedAt          time.Time `json:"updated_at"`
}
